import 'package:bruno/bruno.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_search/flutter_baidu_mapapi_search.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:untitled/Page/local_map/custom_drawer.dart';
import 'package:untitled/dao/dart_api.dart';
import 'package:untitled/widget/anchor_point.dart';
import 'package:untitled/widget/bike/bike_information_drop_down_menu.dart';
import 'package:untitled/widget/line_detail_widget.dart';

import '../../widget/location_display/location_display_widget.dart';
import 'edit_foundition.dart';

class BaiduMapPage extends StatefulWidget {
  const BaiduMapPage({super.key});

  @override
  State<BaiduMapPage> createState() => _BaiduMapPageState();
}

class _BaiduMapPageState extends State<BaiduMapPage> {
  final CustomDrawerController drawerController =
      Get.put(CustomDrawerController());
  final BikeInformationDropDownMenuController bikeInfoController =
      Get.put(BikeInformationDropDownMenuController());

  BaiduLocation _loationResult = BaiduLocation();
  late BMFMapController _myMapController;
  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();
  bool _suc = false;
  BMFMarker? _lastMarket;
  double? _newCenterLag; //中心点经度
  double? _newCenterLng; //中心点纬度
  double? _oldCenterLag; //中心点经度
  double? _oldCenterLng; //中心点纬度
  bool ticketTag = true; //是否是第一次定位
  List<BMFMarker> markerCatch = [];
  List<BMFMarker> newMarkList = [];
  List<BMFMarker> oldMarkList = [];
  var markerDetailedInfo = [];
  var markerInfo = []; //存放所有平台从数据库中读取数据时读到的内容
  List<BMFMarker> mapMarkers = []; // 存储所有地图上显示的marker点
  double listAreaHeight = 200.0; //设置交通工具信息列表的高度
  RxMap selectedInfos = {"id": "", "address": "", "type": "", "info": []}.obs;
  var _lineCount = 0;
  final TextEditingController _searchController = TextEditingController();
  BMFSuggestionInfo selectedLocationInfo = BMFSuggestionInfo();



  @override
  void initState() {
    super.initState();

    ///接受定位回调
    _myLocPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
      setState(() {
        _loationResult = result;
        _locationFinish();
        drawerController.currentLocation.value =
            _loationResult.getMap()["locationDetail"];
        _myLocPlugin.stopLocation();
        _myLocPlugin.stopLocation();
      });
    });
    //开启定时任务
    _anchorPointActionHandler();
    _locationAction();
    _startLocation();
  }

//  定时任务,处理锚点动画

  void _anchorPointActionHandler() async {
    while (ticketTag) {
      if (_newCenterLag != _oldCenterLag || _newCenterLng != _oldCenterLng) {
        //如果新值和旧值在200毫秒内不相等,就说明数据有变化,只要有变化就继续播放动画,并且同步一次数据
        if (!drawerController.playing.value) {
          drawerController.playing.value = true;
        }
        _oldCenterLag = _newCenterLag;
        _oldCenterLng = _newCenterLng;
      } else {
        if (drawerController.playing.value) {
          drawerController.playing.value = false;
          // 更新结束，请求后端，刷新数据锚点
          // TODO:
          markerCatch = [];
          markerInfo = [];
          if (!drawerController.isBusSelected.value &&
              !drawerController.isbikeParkSelected.value &&
              !drawerController.isSubwaySelected.value) {
            setState(() {
              _myMapController.removeMarkers(mapMarkers);
            });
            mapMarkers = [];
            newMarkList = [];
            oldMarkList = [];
            markerDetailedInfo = [];
            await Future.delayed(const Duration(milliseconds: 300));
            continue;
          }
          if (drawerController.isBusSelected.value) {
            await addBusSiteMaker(_newCenterLag, _newCenterLng);
          }

          if (drawerController.isbikeParkSelected.value) {
            await addByciclePark(_newCenterLag, _newCenterLng);
          }

          if (drawerController.isSubwaySelected.value) {
            await addSubway(_newCenterLag, _newCenterLng);
          }
          //同步数据

          List<BMFMarker> mk = [];
          for (BMFMarker oldMarker in oldMarkList) {
            //这里存放了老的和新的数据之间相同的数据
            for (BMFMarker newMarker in newMarkList) {
              if (oldMarker.title == newMarker.title) {
                mk.add(oldMarker);
              }
            }
          }
          List<BMFMarker> rm = [];
          bool flagRM = false;
          for (BMFMarker marker in oldMarkList) {
            flagRM = false;
            for (BMFMarker mkch in mk) {
              if (marker.title == mkch.title) {
                flagRM = true;
                break;
              }
            }

            if (!flagRM) {
              rm.add(marker);
            }
          }
          setState(() {
            _myMapController.removeMarkers(rm);
          });

          List<BMFMarker> add = [];
          bool flagADD = false;
          for (BMFMarker marker in newMarkList) {
            flagADD = false;
            for (BMFMarker mkch in mk) {
              if (marker.title == mkch.title) {
                flagADD = true;
              }
            }
            if (!flagADD) {
              add.add(marker);
            }
          }
          setState(() {
            _myMapController.addMarkers(add);
            mapMarkers.addAll(add);

            bool removeFlag = true;
            List<BMFMarker> removeList = [];
            for (var i = 0; i < mapMarkers.length; i++) {
              removeFlag = true;
              for (var j = 0; j < newMarkList.length; j++) {
                if (mapMarkers[i].title == newMarkList[j].title) {
                  removeFlag = false;
                  break;
                }
              }
              if (removeFlag) {
                _myMapController.removeMarker(mapMarkers[i]);
                removeList.add(mapMarkers[i]);
              }
            }
            for (var element in removeList) {
              mapMarkers.remove(element);
            }
          });

          // 更新 oldMarkList
          oldMarkList = List.from(newMarkList);
        }
      }
      await Future.delayed(const Duration(milliseconds: 300));
    }
  }

  @override
  void dispose() {
    super.dispose();
    ticketTag = false;
    _stopLocation();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> resultWidgets = [];

    if (_loationResult.locTime != null) {
      _loationResult.getMap().forEach((key, value) {
        resultWidgets.add(_resultWidget(key, value));
      });
    }

    return Stack(children: [
      _createMapContainer(context),

      // Container(height: 20),

      //上拉菜单
      Positioned(
        left: 0,
        right: 0,
        bottom: -10,
        child: CustomDrawer(
          onDrawerClosed: () {},
          onDrawerOpened: () {},
          onRefresh: () {
            //点击刷新之后触发刷新地图
            _locationAction();
            _startLocation();
          },
        ),
      ),
      Center(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(0, 0, 0, 50),
          child: AnchorPoint(),
        ),
      ),
      Padding(
          padding: const EdgeInsets.fromLTRB(0, 100, 0, 0),
          child: _createMsgBar()),

      Container(
        color: Colors.white,
        padding: const EdgeInsets.fromLTRB(0, 40, 0, 0),
        child: RoundedSearchField(
          onSearchResult: (result) {
            selectedLocationInfo = result;
            _myMapController.setCenterCoordinate(result.location!, true);
            //显示导航按钮
            drawerController.isShowNavBtn.value = true;
          },
        ),
      ),
      //顶部信息
    ]);
  }

  Widget _createMapContainer(context) {
    return Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: BMFMapWidget(
          onBMFMapCreated: (controller) {
            _onBMFMapCreated(controller);
          },
          mapOptions: _initMapOptions(),
        ));
  }

  Widget _resultWidget(key, value) {
    return Center(
      child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('$key:' ' $value'),
          ]),
    );
  }

  void _locationAction() async {
    /// 设置android端和ios端定位参数
    /// android 端设置定位参数
    /// ios 端设置定位参数
    Map iosMap = _initIOSOptions().getMap();
    Map androidMap = _initAndroidOptions().getMap();

    _suc = await _myLocPlugin.prepareLoc(androidMap, iosMap);
  }

  /// 设置地图参数
  BaiduLocationAndroidOption _initAndroidOptions() {
    BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
        coorType: 'bd09ll',
        locationMode: BMFLocationMode.hightAccuracy,
        isNeedAddress: true,
        isNeedAltitude: true,
        isNeedLocationPoiList: true,
        isNeedNewVersionRgc: true,
        isNeedLocationDescribe: true,
        openGps: true,
        scanspan: 4000,
        coordType: BMFLocationCoordType.bd09ll);
    return options;
  }

  BaiduLocationIOSOption _initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
        coordType: BMFLocationCoordType.bd09ll,
        BMKLocationCoordinateType: 'BMKLocationCoordinateTypeBMK09LL',
        desiredAccuracy: BMFDesiredAccuracy.best,
        allowsBackgroundLocationUpdates: true,
        pausesLocationUpdatesAutomatically: false);
    return options;
  }

  // /// 启动定位
  Future<void> _startLocation() async {
    _suc = await _myLocPlugin.startLocation();
  }

  /// 停止定位
  void _stopLocation() async {
    _suc = await _myLocPlugin.stopLocation();
  }

  ///定位完成添加mark
  void _locationFinish() {
    /// 创建BMFMarker
    if (_lastMarket != null) {
      _myMapController.removeMarker(_lastMarket!);
    }
    BMFMarker marker = BMFMarker.icon(
        position: BMFCoordinate(
            _loationResult.latitude ?? 0.0, _loationResult.longitude ?? 0.0),
        title: 'flutterMaker',
        identifier: 'flutter_marker',
        icon: 'assets/img/icon/icon_client_location.png');
    _lastMarket = marker;

    /// 添加Marker
    _myMapController.addMarker(marker);

    ///设置中心点
    _updateMapCenter(_loationResult.latitude, _loationResult.longitude);
    // _myMapController
    // .updateMapOptions(BMFMapOptions(center: BMFCoordinate(39.90, 116.40)));
  }

  //设置地图中心点
  _updateMapCenter(lat, lng) {
    _myMapController.setCenterCoordinate(
        BMFCoordinate(lat ?? 0.0, lng ?? 0.0), false,
        animateDurationMs: 1000);
  }

  /// 设置地图参数
  BMFMapOptions _initMapOptions() {
    BMFMapOptions mapOptions = BMFMapOptions(
        showZoomControl: false,
        // center: BMFCoordinate(39.917215, 116.380341),
        zoomLevel: 18,
        mapPadding: BMFEdgeInsets(top: 0, left: 0, right: 0, bottom: 0));
    return mapOptions;
  }

  /// 创建完成回调
  void _onBMFMapCreated(BMFMapController controller) {
    _myMapController = controller;
    _myMapController.showUserLocation(true);
    //设置地图样式
    _loadCustomMapStyle();
    //设置地图区域改变完成时的回调
    _myMapController.setMapRegionDidChangeCallback(
        callback: (BMFMapStatus mapStatus) {
      _newCenterLag = mapStatus.targetGeoPt?.latitude;
      _newCenterLng = mapStatus.targetGeoPt?.longitude;
      if (!drawerController.playing.value) {
        drawerController.playing.value = true;
      }
    });

    /// 地图加载回调
    _myMapController.setMapDidLoadCallback(callback: () {});
    //加载Marker点击事件
    _myMapController.setMapClickedMarkerCallback(callback: (BMFMarker marker) {
      //更新地图中心点
      _updateMapCenter(marker.position.latitude, marker.position.longitude);
      print("更新地图中心点");
      var infoMap = mapMarkers.firstWhere((element) => element.id == marker.id);
      print("执行完了markerDetailedInfo获取数据的方法");

      try {
        var info = markerDetailedInfo
            .firstWhere((element) => element["address"] == infoMap.title);
        print(info);
        selectedInfos.value["id"] = info["id"];
        selectedInfos.value["address"] = info["address"];
        selectedInfos.value["type"] = info["type"];
        selectedInfos.value["info"] = info["info"];
        bikeInfoController.stationName.value = info["address"];
        drawerController.showLineDetail.value = true;
      } catch (_) {
        setState(() {
          BrnToast.show("该站点数据异常，请尝试刷新后再试", context);
        });
      }
    });
  }

  //加载自定义地图样式
  void _loadCustomMapStyle() async {
    BMFCustomMapStyleOption customMapStyleOption = BMFCustomMapStyleOption(
        customMapStyleID: "79b9301d31d5aff9483b0b451e43e2a7");
    _myMapController.setCustomMapStyleWithOptionPath(
        customMapStyleOption: customMapStyleOption,
        preload: (path) {
          print('preload');
        },
        success: (path) {
          print("success");
        },
        error: (errCode, path) {
          print("error");
        });
  }

  //生成Maker锚点
  getMarkerAnchor(
      res, type, addressNameFlag, latFlag, lngFlag, iconPath) async {
    for (var site in res) {
      markerInfo.add(site);
      BMFMarker marker;
      if (type == "busSite") {
        marker = BMFMarker.icon(
            position: BMFCoordinate(
                double.parse(site["latLng"][0].toString()) ?? 0.0,
                double.parse(site["latLng"][1].toString()) ?? 0.0),
            title: site[addressNameFlag],
            identifier: '$type',
            enabled: true,
            icon: iconPath);
      } else {
        marker = BMFMarker.icon(
            position: BMFCoordinate(double.parse(site[latFlag]) ?? 0.0,
                double.parse(site[lngFlag]) ?? 0.0),
            title: site[addressNameFlag],
            identifier: '$type',
            enabled: true,
            icon: iconPath);
      }
      if (newMarkList.length == 0) newMarkList.add(marker);
      bool renewFlag = false;
      for (int i = 0; i < newMarkList.length; i++) {
        if (newMarkList[i].title == marker.title) {
          renewFlag = true;
          break;
        }
      }
      if (!renewFlag) {
        newMarkList.add(marker);
        markerDetailedInfo.add({
          "id": marker.id,
          "address": site[addressNameFlag],
          "type": "$type",
          "info": site
        });
      }
    }
    List<BMFMarker> newList = [];
    bool flag = false;
    for (var item in newMarkList) {
      flag = false;
      for (var info in markerInfo) {
        if (info[addressNameFlag] == null ||
            item.title == info[addressNameFlag]) {
          flag = true;
          break;
        }
      }
      if (flag) {
        newList.add(item);
      }
    }
    newMarkList = newList;

    // var detail = [];
    // //把detail的数据和newMarkList数据同步
    // for (int i = 0;i < markerDetailedInfo.length; i++) {
    //   for (var j = 0; j < mapMarkers.length; j++) {
    //     if (mapMarkers[j].title == markerDetailedInfo[i]["address"] || markerDetailedInfo[i]["type"] != type) {
    //       detail.add(markerDetailedInfo[i]);
    //       break;
    //     }
    //   }
    //
    // }
    // if(mapMarkers.length != 0) {
    //   markerDetailedInfo = detail;
    // }
    // print("markerDetailedInfo的大小：${markerDetailedInfo.length}");
  }

  //添加公交车站锚点
  addBusSiteMaker(lat, lng) async {
    var res = await DartAPI.findAllBusStation(lat, lng);
    getMarkerAnchor(res, 'busSite', 'station_Name', null, null,
        'assets/img/icon/icon_bus_site.png');
  }

  //添加共享单车停放点锚点
  addByciclePark(lat, lng) async {
    var res = await _getBycicleParkData(lat, lng);
    getMarkerAnchor(res, 'byciclePark', 'name', 'lat', 'lng',
        'assets/img/icon/icon_bycicle_park.png');
  }

  //加载地铁描点
  addSubway(lat, lng) async {
    var res = await _getSubwayData(lat, lng);
    getMarkerAnchor(res, 'subway', 'station_name', 'lng', 'lat',
        'assets/img/icon/icon_subway.png');
  }

  //获取单车停放点信息
  _getBycicleParkData(lat, lng) async {
    return await DartAPI.findAllByciclePark(lat, lng);
  }

  //获取地铁站点信息
  _getSubwayData(lat, lng) async {
    return await DartAPI.findAllSubway(lat, lng);
  }

  // //根据地铁线路获取站点信息
  // _getSubwayStationData(line) async {
  //   return await DartAPI.findAllSubwayByLine(line);
  // }

  //创建Marker点击后出现的HeaderBar
  Widget _createMsgBar() {
    // ignore: invalid_use_of_protected_member
    return selectedInfos.value['type'] == 'byciclePark'
        ? BikeInformationDropDownMenu()
        : Obx(() {
      if (drawerController.isShowNavBtn.value) {
        return LocationDisplayWidget(
          locationName: selectedLocationInfo.key!,
          cityName: selectedLocationInfo.city!,
          onClose: () {
            print("点击了");
            drawerController.isShowNavBtn.value = false;
          },
        );
      } else {
        return Visibility(
            visible: selectedInfos.value["id"] != "",
            child: SizedBox(
              height: listAreaHeight,
              child: Padding(
                  padding: const EdgeInsets.fromLTRB(10, 20, 10, 5),
                  child: EasyRefresh(
                    bottomBouncing: false,
                    header: ClassicalHeader(
                      refreshText: "下拉加载更多",
                      refreshReadyText: "松开刷新",
                      refreshedText: "加载成功",
                      refreshFailedText: "加载失败",
                      refreshingText: "加载中...",
                      noMoreText: "没有更多了",
                    ),
                    footer: ClassicalFooter(
                      noMoreText: "没有更多了",
                      loadText: "加载更多",
                      loadingText: "加载中...",
                      loadedText: "加载成功",
                      loadReadyText: "松开加载",
                      loadFailedText: "加载失败",
                    ),
                    child: CustomScrollView(
                      slivers: [
                        SliverToBoxAdapter(
                          child: Container(
                            padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(5)),
                            child: Column(
                              children: [
                                Row(
                                  mainAxisAlignment:
                                  MainAxisAlignment.spaceBetween,
                                  children: [
                                    SizedBox(
                                        width: 260,
                                        child: Text(
                                          // ignore: invalid_use_of_protected_member
                                          selectedInfos.value["address"],
                                          style: const TextStyle(
                                              fontSize: 22,
                                              color: Colors.blue),
                                          overflow: TextOverflow
                                              .ellipsis, // 显示省略号
                                          maxLines: 1, // 最多显示一行
                                        )),
                                    IconButton(
                                        onPressed: () {
                                          setState(() {
                                            selectedInfos.value["id"] = "";
                                            _lineCount = 0;
                                            listAreaHeight = 200.0;
                                          });
                                        },
                                        icon: const Icon(
                                          Icons.close,
                                          size: 20,
                                          color: Color.fromARGB(
                                              255, 240, 240, 240),
                                        )),
                                  ],
                                ),
                                BrnLine(),
                                Row(
                                  mainAxisAlignment:
                                  MainAxisAlignment.spaceBetween,
                                  children: [
                                    Align(
                                      alignment: Alignment.centerLeft,
                                      child: Row(
                                        mainAxisAlignment:
                                        MainAxisAlignment.start,
                                        children: _getStationTag(),
                                      ),
                                    ),
                                    Align(
                                      alignment: Alignment.centerRight,
                                      child: TextButton(
                                          onPressed: () {
                                            if (listAreaHeight == 200.0) {
                                              if (selectedInfos['type'] ==
                                                  'busSite') {
                                                setState(() {
                                                  listAreaHeight = 520.0;
                                                  _lineCount = selectedInfos
                                                      .value["info"]
                                                  ["line_Id"]
                                                      .length;
                                                });
                                              }
                                              if (selectedInfos['type'] ==
                                                  'subway') {
                                                setState(() {
                                                  listAreaHeight = 520.0;
                                                  _lineCount = 1;
                                                });
                                              }
                                              if (selectedInfos['type'] ==
                                                  'park') {
                                                setState(() {
                                                  listAreaHeight = 520.0;
                                                  _lineCount = 1;
                                                });
                                              }
                                            } else {
                                              setState(() {
                                                listAreaHeight = 200.0;
                                                _lineCount = 0;
                                              });
                                            }
                                          },
                                          child: Text(
                                              listAreaHeight == 520.0
                                                  ? "收起"
                                                  : "实时信息")),
                                    )
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                        // 刷新公交信息
                        SliverList(
                          delegate: SliverChildBuilderDelegate(
                                (context, index) {
                              return LineDetailWidget(
                                  typeOfVehicle:
                                  selectedInfos.value["type"],
                                  localStationName:
                                  selectedInfos.value["address"],
                                  busLineName: selectedInfos.value["info"]
                                  ["line_Id"][index]);
                            },
                            childCount: _lineCount,
                          ),
                        ),
                      ],
                    ),
                    onRefresh: () async {
                      //刷新公交信息
                    },
                  )),
            )
        );
      }
    });
  }
  //更新头部Bar数据
  _getStationTag() {
    List<BrnTagCustom> tagList = [];
    switch (selectedInfos.value["type"]) {
      case "busSite":
        {
          List stationTag = selectedInfos.value["info"]["line_Id"];
          if (stationTag != null) {
            for (String tag in stationTag) {
              String tagName = "";
              if (tag.contains("000")) {
                tagName = "${tag.split("000")[0]}路" +
                    (tag.split("000")[1] == 1 ? "A" : "B");
              } else {
                tagName = "$tag路";
              }
              BrnTagCustom custom = BrnTagCustom(
                  tagText: "$tagName",
                  tagBorderRadius: BorderRadius.circular(15),
                  textPadding: const EdgeInsets.all(5));
              tagList.add(custom);
            }
          }
        }
        break;
      case "subway":
        {
          List stationTag = selectedInfos.value["info"]["line_Id"];
          for (String tag in stationTag) {
            BrnTagCustom custom = BrnTagCustom(
                tagText: "$tag号线",
                tagBorderRadius: BorderRadius.circular(15),
                textPadding: const EdgeInsets.all(5));
            tagList.add(custom);
          }
        }
    }
    return tagList;
  }
}
